package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import java.util.HashMap;
import org.json.JSONException;

public abstract class CheckDetailFragment extends BaseFragment {
  public static final String EXTRA_REQUISITION_ID =
      "com.isunland.managesystem.ui.EXTRA_REQUISITION_ID";
  public static final String EXTRA_DATASTATUS = "com.isunland.managesystem.ui.EXTRA_DATASTATUS";
  public static final String EXTRA_TYPE = "com.isunland.managesystem.ui.EXTRA_TYPE";
  public static final String EXTRA_INTERRUPT = "com.isunland.managesystem.ui.EXTRA_INTERRUPT";
  public static final String EXTRA_FILE = "com.isunland.managesystem.ui.EXTRA_FILE";
  public static final String EXTRA_IFALLOW = "com.isunland.managesystem.ui.EXTRA_IFALLOW";
  public static final int REQUEST_DELETE = 6;
  public static final int REQUEST_SUBMIT = 7;
  public static final String VALUE_OVER = "over";
  public static final String VALUE_UNPUNCH = "unpunch";
  public static final String VALUE_HOLY = "holy";
  public static final String VALUE_TRIP = "trip";
  public static final String VALUE_OUT = "out";
  public static final String VALUE_OFF = "usableExchange";
  protected static final String SICK = "Sick";//病假id
  protected static final String ANNUAL = "Annual";//年假id
  protected static final String EXCHANGEHOLIDAY = "ExchangeHoliday";//调休id
  protected static final String PAIDLEAVE = "PaidLeave";//带薪假id
  protected static final int ADD = 1;
  protected static final int EDIT = 2;
  protected static final int WAIT_CHECK = 3;// 审核中
  protected static final int CHECK_PASS = 4;// 已审核
  protected static final int TODO = 5;//代办流程中跳转过来,只允许保存
  protected static final String TYPE_SAVE = "save";
  protected static final String TYPE_RUN = "run";


  // private static final int REQUEST_ERROR = 8;
  protected String mId;
  protected String mDataStatus;
  protected int mMenuType;
  protected String mType;
  protected String mRunId;
  protected String mFileUrl;
  protected String ifAllowSupplement;

  public static Fragment newInstance(String id, String type, String runId, String file,
      String dataStatus, String ifAllowSupplement) {
    Bundle args = new Bundle();

    args.putString(EXTRA_TYPE, type);
    args.putString(EXTRA_REQUISITION_ID, id);
    args.putString(EXTRA_INTERRUPT, runId);
    args.putString(EXTRA_FILE, file);
    args.putString(EXTRA_DATASTATUS, dataStatus);
    args.putString(EXTRA_IFALLOW, ifAllowSupplement);
    CheckDetailFragment fragment = null;
    /**加班申请*/
    if (CheckDetailFragment.VALUE_OVER.equals(type)) {
      fragment = new CheckOverFragment();
    }
    /**差旅申请*/
    if (CheckDetailFragment.VALUE_TRIP.equals(type)) {
      fragment = new CheckTripFragment();
    }
    /**请假申请*/
    if (CheckDetailFragment.VALUE_HOLY.equals(type)) {
      fragment = new CheckHolyFragment();
    }
    /**外出工作申请*/
    if (CheckDetailFragment.VALUE_OUT.equals(type)) {
      fragment = new CheckOutFragment();
    }
    /**未打卡申请*/
    if (CheckDetailFragment.VALUE_UNPUNCH.equals(type)) {
      fragment = new CheckUnpunchFragment();
    }/**可用调休申请*/
    if (CheckDetailFragment.VALUE_OFF.equals(type)) {
      fragment = new CheckOffFragment();
    }
    if (fragment != null) {

      fragment.setArguments(args);
    }
    return fragment;
  }

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mType = getArguments().getString(EXTRA_TYPE);
    mRunId = getArguments().getString(EXTRA_INTERRUPT);
    mFileUrl = getArguments().getString(EXTRA_FILE);
    mId = getArguments().getString(EXTRA_REQUISITION_ID);
    mDataStatus = getArguments().getString(EXTRA_DATASTATUS);
    ifAllowSupplement = getArguments().getString(EXTRA_IFALLOW);
    if (null != mDataStatus && mDataStatus.equalsIgnoreCase("checkPass")) {
      mMenuType = CHECK_PASS;
    } else if (null != mDataStatus && mDataStatus.equalsIgnoreCase("waitCheck")) {
      mMenuType = WAIT_CHECK;
    } else if (null != mDataStatus && mDataStatus.equalsIgnoreCase("todo")) {
      mMenuType = TODO;
    } else {
      if (!TextUtils.isEmpty(mId)) {

        mMenuType = EDIT;
      } else {

        mMenuType = ADD;
      }
    }
    mActivity.invalidateOptionsMenu();
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    switch (mMenuType) {
      case ADD:
        inflater.inflate(R.menu.menu_save_submit, menu);
        break;
      case EDIT:
        inflater.inflate(R.menu.menu_save_submit_delete, menu);
        break;
      case WAIT_CHECK:
        inflater.inflate(R.menu.menu_stop, menu);
        break;
      case TODO:
        //只允许保存
        inflater.inflate(R.menu.menu_save_submit, menu);
        menu.getItem(1).setVisible(false);
        break;
      case CHECK_PASS:

        break;

      default:
        break;
    }

    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:

        //                if (NavUtils.getParentActivityName(getActivity()) != null) {
        //                    NavUtils.navigateUpFromSameTask(getActivity());
        //                }
        getActivity().finish();

        return true;
      case R.id.menu_item_save:
        //			boolean isCorrect = isCorrectInput();
        //			if (isCorrect) {

        volleyPostSave(TYPE_SAVE);
        //			}
        return true;
      case R.id.menu_item_submit:
        boolean isCorrectSubmit = isCorrectInput();
        if (isCorrectSubmit) {
          showDialog(REQUEST_SUBMIT);
        }

        return true;
      case R.id.menu_item_delete:
        showDialog(REQUEST_DELETE);
        return true;

      // 终止流程
      case R.id.menu_item_stop:
        interruptProcess();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  /**
   * 有的公司不让补填。所以要隐藏掉补填界面
   * 在子fragment里的onCreateView或onViewCreate方法中调用。View
   */
  protected void laterViewVisiblity(View v, String ifAllowSupplement) {

    boolean isShow = true;//默认都可以补填
    if (ifAllowSupplement == null || TextUtils.isEmpty(ifAllowSupplement)) {
      isShow = true;
    } else if ("T".equalsIgnoreCase(ifAllowSupplement)) {
      //允许补填
      isShow = true;
    } else if ("F".equalsIgnoreCase(ifAllowSupplement)) {
      //不允许补填
      isShow = false;
    }
    if (v == null) return;
    RadioGroup later = (RadioGroup) v.findViewById(R.id.rg_type);
    TextView llMiddleLine = (TextView) v.findViewById(R.id.ll_line);
    if (later == null) return;
    if (isShow) {
      later.setVisibility(View.VISIBLE);
    } else {
      later.setVisibility(View.GONE);
      llMiddleLine.setVisibility(View.VISIBLE);
    }
  }

  /**
   * TODO终止流程
   */
  private void interruptProcess() {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TASK_STOP);
    HashMap<String, String> params = new HashMap<>();
    if (mRunId != null && !("".equalsIgnoreCase(mRunId))) {
      params.put("runId", mRunId);

      mActivity.volleyPost(url, params, new VolleyResponse() {

        @Override public void onVolleyResponse(String arg0) throws JSONException {
          MyUtils.dismissDialog();
          try {

            SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
            String successType = successsMessage.getResult();
            if (successType.equals("1")) {
              Toast.makeText(getActivity(), R.string.interruptSuccess, Toast.LENGTH_SHORT).show();
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
            } else {
              Toast.makeText(getActivity(), R.string.interruptFail, Toast.LENGTH_SHORT).show();
            }
          } catch (Exception e) {
            LogUtil.e("error", e);
            Toast.makeText(getActivity(), R.string.interruptFail, Toast.LENGTH_SHORT).show();
          }
        }

        @Override public void onVolleyError(VolleyError arg0) {
          LogUtil.e("VolleyError", arg0);
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
        }
      });
    }
  }

  private void showDialog(int type) {
    DialogFragment dialog;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    switch (type) {
      case REQUEST_SUBMIT:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.start_up_hint);
        break;
      case REQUEST_DELETE:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm);

        break;
      default:
        return;
    }

    // CustomerDialogFragment dialog = CustomerDialogFragment
    // .newInstance(type);
    dialog.setTargetFragment(this, type);
    dialog.show(fm, "");
  }

  protected void showErrorDialog(String message) {
    Builder builder = new Builder(getActivity()).setMessage(message)
        .setTitle("提示")
        .setPositiveButton("确定", new OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            // Auto-generated method stub

          }
        });
    builder.create().show();
  }

  protected abstract void volleyPostSave(String typeSave);

  protected abstract boolean isCorrectInput();
}
